<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			p{
				color: blue;
			}
		</style>
		
	</head>
	<body onload="init()">
		学院：<select id="c1" onchange="change()"></select>
		专业：<select id="c2"></select>
		<p>所选择专业：<span id="selection"></span></p>
		
		<script type="text/javascript">
			const c1 = document.querySelector("#c1")
			const c2 = document.querySelector("#c2")
			const selectionDisplay = document.querySelector("#selection");
			
			let school=[];
			function init(){
				let xhr=new XMLHttpRequest();
				xhr.open("GET","school.json","true")
				xhr.send();
				xhr.onreadystatechange=function(){
					if(xhr.readyState==4&&xhr.status==200){
						let data=xhr.responseText
						school=JSON.parse(data);
						for (let i = 0; i < school.length; i++) {
							c1.options[i]=new Option(school[i].name)
						}
						for (let i = 0; i < school[0].majors.length; i++) {
							c2.options[i]=new Option(school[0].majors[i])
						}
						updateSelection();
					}
				}
			}
			
			function change(){
				let index = c1.selectedIndex 
				c2.length = 0 
				for (let i = 0; i < school[index].majors.length; i++) {
					c2.options[i] = new Option(school[index].majors[i])
					}
					updateSelection();
			}
			
			c2.addEventListener('change', updateSelection);//通过监听,确保专业下拉也随着变化
			function updateSelection(){
				let Name = school[c1.selectedIndex].name;
				let major = school[c1.selectedIndex].majors[c2.selectedIndex];
				selectionDisplay.textContent = Name + "·" + major;
			}
		</script>
	</body>
</html>
